﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using Microsoft.Win32;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.CompilerServices;

namespace NetCoreClass
{
    public class WebHttp
    {
        public string GetRequest(string Url, string user, string pwd, string accept)
        {
            Encoding MsgEncode = Encoding.UTF8;

            if (string.IsNullOrEmpty(Url))
            {
                throw new ArgumentNullException("Url");
            }
            if (MsgEncode == null)
            {
                throw new ArgumentNullException("MsgEncoding");
            }

            string username = user;
            string password = pwd;
            string usernamePassword = username + ":" + password;
            CredentialCache mycache = new CredentialCache();
            mycache.Add(new Uri(Url), "Digest", new NetworkCredential(username, password));

            // Logger.INFO(GetType().ToString(), "PostRequest", "POST HTTP请求,创建短信请求", string.Empty);
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(new Uri(Url));
            Request.Credentials = mycache;
            Request.Headers.Add("Authorization", "Digest" + Convert.ToBase64String(MsgEncode.GetBytes(usernamePassword)));

            Request.Method = "GET";
           Request.Timeout = 60000;  
            Request.ContentType = "application/x-www-form-urlencoded";
            Request.Accept = accept;
            return GetHttpWebResponse(Request);
        }
        //private string GetHttpWebResponse(WebRequest webRequest)
        //{
        //    StreamReader responseReader = null;
        //    string responseData;
        //    try
        //    {
        //        responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        //        responseData = responseReader.ReadToEnd();
        //        responseReader.Close();
        //        webRequest.GetResponse().GetResponseStream().Close();
        //    }
        //    catch (WebException wex)
        //    {
        //        //responseData = exp.Message;
        //        //responseReader.Close();
        //        var webResp = wex.Response as HttpWebResponse;
        //        if (webResp != null)
        //        {
        //            responseData = RetrieveResponse(webResp);
        //        }
        //        else
        //        {
        //            responseData = null;
        //        }

        //    }
        //    finally
        //    {

        //        // ;
        //    }

        //    return responseData;
        //}
        private string GetHttpWebResponse(WebRequest webRequest)
        {
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
 
            string ret = response.StatusCode.ToString();

            
            System.IO.Stream stream = response.GetResponseStream();

            string str = "";
            int getNum = 0;//实际读取的字节数
            byte[] buf = new byte[1024];//缓冲区
            getNum = stream.Read(buf, 0, 1024);//预读取
            while (getNum > 0)//度过读取到
            {
                str += System.Text.Encoding.UTF8.GetString(buf, 0, getNum);//转换为strin,注意要使用getNum,而不是1024
                getNum = stream.Read(buf, 0, 1024);//再读取
            }
            stream.Close();
            response.Close();

            return str;
        }

        private string RetrieveResponse(WebResponse webResponse)
        {
            var respContent = string.Empty;
            var respStream = webResponse.GetResponseStream();
            using (StreamReader reader = new StreamReader(respStream, Encoding.UTF8))
            {
                respContent = reader.ReadToEnd();
            }
            webResponse.Close();

            return respContent;
        }
        public string WebRequestGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 60000;
            request.ServicePoint.Expect100Continue = false;
            return GetHttpWebResponse(request);

        }
        public string WebRequestGet(string url, string accept)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            // request.Headers.Add("Accept" ,"application/json");
            request.Accept = accept;
            request.ServicePoint.Expect100Continue = false;
            request.Timeout = 60000;
            return GetHttpWebResponse(request);

        }

       
        /*
         * 存储图片到指定路径
         * url：图片网址
         * path:存储路径
         * 
         */ 
        public string WebRequestSavePic(string url,string path)
        {
            string filepath = DateTime.Now.ToString("yyyyMMddhhmmss") + RandomString.GetRandomString(6) + ".jpg";
            filepath = Path.Combine(path, filepath);
            WebClient mywebclient = new WebClient();
            mywebclient.DownloadFile(url, filepath);
            return filepath;
        }
        public string WebRequestPost(string url, string postData)
        {
            var httpWebRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            httpWebRequest.Method = "POST";
            httpWebRequest.ServicePoint.Expect100Continue = false;
            httpWebRequest.Timeout = 60000;
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";

            return GetHttpWebResponse(httpWebRequest, postData);
        }
        public string WebRequestPost(string url, string postData,string type)
        {
            var httpWebRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            httpWebRequest.Method = "POST";
            httpWebRequest.ServicePoint.Expect100Continue = false;
            httpWebRequest.Timeout = 60000;
            httpWebRequest.ContentType = type;

            return GetHttpWebResponse(httpWebRequest, postData);
        }
        private string GetHttpWebResponse(WebRequest httpWebRequest, string postData)
        {
            var requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
            try
            {
                requestWriter.Write(postData);
            }
            finally
            {
                requestWriter.Close();
            }
            return GetHttpWebResponse(httpWebRequest);
        }
        public string WebRequestPostFile(string url, List<ListParams> paras, List<ListParams> files)
        {
            HttpWebRequest httpWebRequest ;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                Console.WriteLine(ServicePointManager.SecurityProtocol);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 ;
                httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                httpWebRequest.ProtocolVersion = HttpVersion.Version10;

            }
            else
            {
                httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
            }
            StreamReader responseReader = null;
            string responseData = "";
            Stream requestStream = null;

            try
            {
               
              //  httpWebRequest.ProtocolVersion = new Version(1, 0);
                //httpWebRequest.ServicePoint.Expect100Continue = false;
                httpWebRequest.Timeout = 60000;
                string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                httpWebRequest.Method = "POST";
                httpWebRequest.KeepAlive = true;
                httpWebRequest.Expect = "";
                // httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
                requestStream = httpWebRequest.GetRequestStream(); //写入请求数据

                int content_length = 0;
                            
                //request.Credentials = CredentialCache.DefaultCredentials;
               

                MemoryStream stream = new MemoryStream();

               
                if (files != null)
                {
                    byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                    byte[] enterER = Encoding.ASCII.GetBytes("\r\n");
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: \"{2}\"\r\n\r\n";
                    foreach (ListParams param in files)
                    {
                        requestStream.Write(line, 0, line.Length);
                        string name = param.Name;
                        string filePath = param.Value;
                        string file = Path.GetFileName(filePath);
                        string contentType = GetContentType(file);
                        string header = string.Format(headerTemplate, name, file, contentType);
                        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                        requestStream.Write(headerbytes, 0, headerbytes.Length);
                        //content_length += headerbytes.Length;
                        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        byte[] buffer = new byte[1024];
                        int bytesRead = 0;

                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                            //content_length += bytesRead;
                        }

                        fileStream.Close();
                        requestStream.Write(enterER, 0, enterER.Length);
                    }
                }   

                    //写入参数

                    if (paras != null)
                {
                    string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n";    //自带项目分隔符
                    foreach (var key in paras)
                    {
                        string s = string.Format(format, key.Name, key.Value);
                        byte[] data = Encoding.UTF8.GetBytes(s);
                        requestStream.Write(data, 0, data.Length);
                    }

                }


                //memStream.Write(boundarybytes, 0, boundarybytes.Length);
                byte[] foot_boundary = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
                requestStream.Write(foot_boundary, 0, foot_boundary.Length);

                
                        // requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                        //content_length += boundarybytes.Length;
                     
                
                //httpWebRequest.ContentLength =content_length;
                //  httpWebRequest.SendChunked = true;

                //memStream.Position = 0;
                //byte[] tempBuffer = new byte[memStream.Length];
                //memStream.Read(tempBuffer, 0, tempBuffer.Length);
                //memStream.Close();
                //requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
               // requestStream = null;
               
                    responseReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch (Exception exp)
            {
                return exp.Message;
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                    requestStream = null;
                }
                if (responseReader != null)
                {
                    responseReader.Close();
                    responseReader = null;
                }
                //httpWebRequest.GetResponse().GetResponseStream().Close();
                httpWebRequest = null;
            }
            return responseData;
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受 
        }
        private string GetContentType(string fileName)
        {
            string contentType = "application/octetstream";
            //string ext = Path.GetExtension(fileName).ToLower();
            //RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(ext);
             
            //if (registryKey != null && registryKey.GetValue("Content Type") != null)
            //{
            //     contentType = registryKey.GetValue("Content Type").ToString();
            //}
            return contentType;
        }
        #region 从网上下载文件，以指定文件名保存

        /// <summary>s
        /// 从网上下载文件存在本地
        /// </summary>
        /// <param name="url">文件网址</param>
        /// <param name="filepath">本地存储路径</param>
        /// <returns>文件路径</returns>
        public string WebRequestSaveFile(string url, string filepath)
        {
            WebClient mywebclient = new WebClient();
            mywebclient.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
            mywebclient.DownloadFile(url, filepath);
            return filepath;
        }
        #endregion

    }
}
